import { defineStore } from 'pinia'
import { login } from '@/api/login'
import router from '@/router'
import { setTokenTime } from '@/utils/auth'

export const useLoginStore = defineStore('login', {
  state: () => {
    return {
      token: '',
      sideType: true,
      lang: localStorage.getItem('lang') || 'zh'
    }
  },

  getters: {
    getToken: (state) => {
      return state.token
    },
    getSideType: (state) => {
      return state.sideType
    },
    getLang: (state) => {
      return state.lang
    }
  },

  actions: {
    // 登录
    async addCookie(value) {
      const data = await login(value)
      const { token } = data
      this.token = token
      setTokenTime()
      router.replace('/')
    },

    // 退出
    async logout() {
      this.token = ''
      localStorage.clear()
      router.replace('/login')
    },

    // 伸缩左边菜单栏
    changeSideType() {
      this.sideType = !this.sideType
    },

    // 中英切换
    changeLang(lang) {
      this.lang = lang
    }
  },

  // 开启数据缓存
  persist: {
    enabled: true,
    strategies: [
      {
        // key: 'my_project', // key可以自己定义，不填的话默认就是这个store的ID
        storage: localStorage, // storage可以填sessionStorage，localStorage
        paths: ['token'] // paths是需要存储的字段，不填就是全部
      }
    ]
  }
})
